<?php
include "DBConnection.php";

//error_reporting(0);

// removes everything after the first underscore (Y)
function removeUnits($string) {
	$string = explode("_", $string);
	$string = $string[0];
	return $string;
}

$connection = new DBConnection();
$connection -> connect();

$trackID = $_REQUEST['trackID'];
$lat = $_REQUEST['lat'];
$long = $_REQUEST['long'];
$alt = $_REQUEST['alt'];
$consumption = $_REQUEST['consumption'];
$speed = $_REQUEST['speed'];
$engineLoad = $_REQUEST['engineLoad'];
$engineCoolantTemperature = $_REQUEST['engineCoolantTemperature'];
$engineRuntime = $_REQUEST['engineRuntime'];
$airTemperature = $_REQUEST['airTemperature'];
$oilTemperature = $_REQUEST['oilTemperature'];
$fuelRate = $_REQUEST['fuelRate'];
$cmv = $_REQUEST['cmv'];
$time = $_REQUEST['time'];

$trackID = intval($trackID);

$query = "SELECT * FROM track WHERE id = ?";
$statement = $connection -> query($query, array($trackID));
if (count($statement -> fetchAll()) > 0) {

	$query = "INSERT INTO track_data (lat, lon, alt, consumption, speed, engineLoad, 
	engineCoolantTemperature, engineRuntime, airTemperature, oilTemperature, fuelRate, cmv, time) 
	VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

	$params1 = array($lat, $long, $alt, $consumption, $speed, $engineLoad, $engineCoolantTemperature, $engineRuntime, $airTemperature, $oilTemperature, $fuelRate, $cmv, $time);
	$params2 = array();
	$firstRun = true;
	foreach ($params1 as $currentParam) {
		$currentParam = removeUnits($currentParam);

		array_push($params2, $currentParam);

	}

	if ($connection -> query($query, $params2)) {
		$query = "INSERT INTO track_track_data (track_id, track_data_id) VALUES (?, LAST_INSERT_ID())";
		if ($connection -> query($query, array($trackID))) {
			echo "{	\"status\" : 200}";
		}
	}
} else {
	echo "{
	\"status\" : 404,
	\"error\" : \"Track not found\"
}";

}
?>